package com.changgou.web.fifter;

import com.changgou.web.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @description:
 * @author: 大佬味的小男孩
 * @date: 2020-07-30 21:43
 **/
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthService authService;

    private static final String LOGIN_URL="http://localhost:8001/api/auth/tologin";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //请求 响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //请求路径rul
        //1）判断当前请求是否为登录请求，是的话，则放行
        String url = request.getURI().getPath();
        //如果URL包括登录则放行
        //|| !UrlFilter.hasAuthorize(url)
        if (url.contains("/api/auth/login") || !UrlFilter.hasAuthorize(url)) {
            return chain.filter(exchange);
        }
        //2) 判断cookie中是否存在信息, 没有的话，拒绝访问
        String jti = authService.getJtiFromCookie(request);
        if (jti == null) {
            /*//拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//没有权限
            return response.setComplete();*/
            //跳转页面
            String reUrl = LOGIN_URL+"?FROM="+request.getURI().getPath();
            return this.toLoginPage(reUrl,exchange);
        }
        //3）判断redis中令牌是否存在，没有的话，拒绝访问
        String jwt = authService.getJwtFromRedis(jti);
        if (jwt == null) {
            //拒绝访问
           /* response.setStatusCode(HttpStatus.UNAUTHORIZED);//没有权限
            return response.setComplete();*/
            String reUrl = LOGIN_URL+"?FROM="+request.getURI().getPath();
            return this.toLoginPage(reUrl,exchange);
        }
        //4)对当前对象进行增强，携带令牌
        request.mutate().header("Authorization", "Bearer " + jwt);
        return chain.filter(exchange);
    }

    //跳转登录页面
    private Mono<Void> toLoginPage(String loginUrl, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location",loginUrl);
        return response.setComplete();
    }

    //返回值越小 优先级越高
    @Override
    public int getOrder() {
        return 1;
    }
}
